package com.iss.yunpan.service.impl;

import com.iss.yunpan.dao.FileDao;
import com.iss.yunpan.entity.FileContent;
import com.iss.yunpan.entity.Users;
import com.iss.yunpan.service.FileService;
import com.obs.services.IObsClient;
import com.obs.services.ObsClient;
import com.obs.services.model.ObsObject;
import com.obs.services.model.TemporarySignatureRequest;
import com.obs.services.model.TemporarySignatureResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

@Service//代表业务逻辑，能够帮助我们实例化
public class FileServiceImpl implements FileService {
    @Autowired
    private HttpSession session;

    private String endPoint="obs.cn-north-4.myhuaweicloud.com";
    private String ak="OP9RXAGXSFPPRSEZVD27";
    private String sk="58KfxQOSUT5YMCXRCSXEEStrFdzTGTKPnFwSqnns";
    private String bucketName = "sanzu";

    @Autowired//依赖注入
    private FileDao dao;

    @Override
    public List<FileContent> getAllFile(String fileName){
        return dao.getAllFile(fileName);
    }

    @Override
    public boolean checkFileContent(String fileName, Integer parentId) {
        FileContent cont=dao.getFileContentByFileNameAndParentId(fileName,parentId);//此处方法可能在老师所讲的文件上传内容中
        if(cont!=null)
        {
            return  true;
        }
        return false;
    }

    @Override
    public void insertFolder(String fileName, Integer parentId) {
        Users user= (Users) session.getAttribute("users");
        if(user!=null&& !"".equals(user.getUserId())){
            FileContent con=new FileContent();
            con.setFileName(fileName);
            con.setParentId(parentId);
            con.setUploadTime(new Date());
            con.setUserId(user.getUserId());
            con.setFileType("文件夹");
            con.setFileAbsolute(fileName);
            dao.insertFile(con);//大写？小写？
// 创建ObsClient实例  //此处方法可能在老师所讲的文件上传内容中
            ObsClient obsClient = new ObsClient(ak, sk, endPoint);//尚未定义
            //来源于pdf 9.5节******************************************************//
            //  final String keySuffixWithSlash = "parent_directory/";
            obsClient.putObject(bucketName, fileName+'/', new ByteArrayInputStream(new byte[0]));//bucketname
//上一行’/‘为自行修改
            //**********************************************//
             //obsClient.putObject(backetName,fileName,input);
        }


    }
    @Override
    public byte[] download(String fileAbsolute) {
        try{
            ObsClient obsClient = new ObsClient(ak, sk, endPoint);
            ObsObject obsObject = obsClient.getObject(bucketName, fileAbsolute);// 读取对象内容
            InputStream input = obsObject.getObjectContent();
            byte[] b = new byte[1024];
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int len;
            while ((len=input.read(b)) != -1){
                bos.write(b, 0, len);
            }
            byte[] out =  bos.toByteArray();
            bos.close();
            input.close();
            return out;
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 如果文件名相同，更新文件；如果文件名不存在，添加文件
     * @param fileName
     * @param input
     * @param parentId
     */
    @Override
    @Transactional
    public void uploadFile(String fileName, InputStream input, String parentId) throws IOException {
        Users user= (Users) session.getAttribute("users");
        if(user!=null&& !user.getUserId().equals(""))
        {
            FileContent con =dao.getFileContentByFileNameAndParentId(fileName,Integer.valueOf(parentId));
            if(con!=null){//存在相同文件名的文件,更新
                con.setFileSize(input.available()+"kb");//新文件大小
                con.setUploadTime(new Date());
                dao.updateFile(con);//更新文件
            }else{//不存在该文件，添加

                FileContent cont = new FileContent();//新建文件
                cont.setFileName(fileName);
                cont.setFileSize(input.available()+"kb");
                cont.setFileAbsolute(fileName);//项目的完整路径
                cont.setFileType(fileName.substring(fileName.lastIndexOf("."),fileName.length()));//截取文件名从。到最后
                cont.setParentId(Integer.valueOf(parentId));//string转int
                cont.setUserId(user.getUserId());//需要从前面的UserId传过来，先固定
                cont.setUploadTime(new Date());
                dao.insertFile(cont);

                //创建ObsClient实例
                ObsClient obsClient=new ObsClient(ak,sk,endPoint);
                obsClient.putObject(bucketName,fileName,input);//input本地文件路
            }

        }
    }

    @Override
    public void renameFile(String fileName, String fileAbsolute,Integer id) {

    }
    //这两个方法也是与文件命名有关的
    @Override
    public void checkFileName(Integer id, String newFileName, String newFileAbsolute, String fileAbsolute)throws IOException {
        //先更新数据库，传过来个id，通过id做一个更新，要更新newfilename以及newFileAbsolute
        dao.updateFileName(id,newFileName,newFileAbsolute,fileAbsolute);            //调整，二十五号下午两点左右
        // 创建ObsClient实例
        //    ObsClient obsClient = new ObsClient(ak, sk, endPoint);
// 重命名对象  由于文件传输的形式，我们换一种思路。//回放八月二十五号早上思路讲解，先流式下载再流式上传   llx
//******************
        // 创建ObsClient实例
        final ObsClient obsClient = new ObsClient(ak, sk, endPoint);
        ObsObject obsObject = obsClient.getObject(bucketName,fileAbsolute);
// 读取对象内容
        System. out .println("Object content:");
        InputStream input = obsObject.getObjectContent();
        byte[] b = new byte[1024];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int len;
        while ((len=input.read(b)) != -1){
            bos.write(b, 0, len);
        }
        System. out .println(new String(bos.toByteArray()));
//        bos.close();
        input.close();
        //**************以下为流式上传内容*****************流式下载部分结束**************llx********
        obsClient.putObject(bucketName, newFileName, new ByteArrayInputStream(bos.toByteArray()));
//        FileInputStream fis = new FileInputStream(new File(fileAbsolute)); // 待上传的本地文件路径，需要指定到具体的文件名
//        obsClient.putObject(bucketName, newFileName, fis);
        bos.close();
//        input.close();
        //*********************流式上传结束************************
    }

    @Override
    public String getFile(String  fileAbsolute) {
        String resultUrl;
        String objectKey = fileAbsolute;
        final ObsClient obsClient = new ObsClient(ak, sk, endPoint);
        TemporarySignatureRequest request = new TemporarySignatureRequest();
        request.setBucketName(bucketName);
        request.setObjectKey(objectKey);
        request.setRequestDate(new Date());
        //五分钟后链接失效
        request.setExpires(60 * 60 * 5);
        TemporarySignatureResponse signature = obsClient.createTemporarySignature(request);
        resultUrl = signature.getSignedUrl();
        System.out.println("[Liu Debug]获取临时URL~Get Temp Url:(preview):转码前url=" + resultUrl);
        return resultUrl;
       }

    @Override
    public void deleteFile(String fileName) {
        FileContent con=new FileContent();
        con.setFileName(fileName);
        dao.deleteFile(con);//更新文件
    }
    @Override
    public void restoreFile(String fileName) {
        FileContent con=new FileContent();
        con.setFileName(fileName);
        dao.restoreFile(con);//更新文件
    }

    @Override
    public void delete(String fileName) {
        FileContent con=new FileContent();
        con.setFileName(fileName);
        dao.delete(con);//更新文件
    }
    @Override
    public List<FileContent> getAllFile1(String fileName) {
        return dao.getAllFile1(fileName);
    }

    @Override
    public String preview(String fileId){
        System.out.println("[Liu Debug]执行预览操作~Now Preview Service:(preview)");
        String resultUrl;
        String objectKey=fileId;
        TemporarySignatureRequest request=new TemporarySignatureRequest();
        request.setBucketName(bucketName);
        request.setObjectKey(objectKey);
        request.setRequestDate(new Date());
//5分钟后链接失效
        request.setExpires(60*60*5);
        IObsClient obsClient = null;
        TemporarySignatureResponse signature=obsClient.createTemporarySignature(request);
        resultUrl=signature.getSignedUrl();
        System.out.println("[Liu Debug]获取临时URL~Get Temp Url: (preview):转码前url="+resultUrl);
        return resultUrl;
    }


}


